<?php
// +----------------------------------------------------------------------
// | User: zq
// +----------------------------------------------------------------------
// | Time: 2021/12/7 11:50
// +----------------------------------------------------------------------

namespace App\Services\Goods;

use App\Inputs\Goods\GoodsListInput;
use App\Models\Goods\FootPrint;
use App\Models\Goods\Goods;
use App\Models\Goods\GoodsAttribute;
use App\Models\Goods\GoodsProduct;
use App\Models\Goods\GoodsSpecification;
use App\Models\Goods\Issue;
use App\Services\BaseService;
use Illuminate\Database\Eloquent\Builder;

class GoodsService extends BaseService
{
    /**
     * 根据id获取商品信息
     * @param  int  $id
     * @return Builder|Goods|null
     */
    public function getGoods(int $id)
    {
        return Goods::query()->find($id);
    }

    public function getGoodsListByIds(array $ids)
    {
        if (empty($ids)) {
            return collect([]);
        }
        return Goods::query()->whereIn('id', $ids)->get();
    }

    /**
     * 获取商品属性
     * @param  int  $goodsId
     * @return Builder[]|GoodsAttribute[]
     */
    public function getGoodsAttribute(int $goodsId)
    {
        return GoodsAttribute::query()->where('goods_id', $goodsId)
            ->get();
    }

    /**
     * 获取商品规格
     * @param  int  $goodsId
     * @return Builder[]
     */
    public function getGoodsSpecification(int $goodsId)
    {
        $spec = GoodsSpecification::query()->where('goods_id', $goodsId)
            ->get()
            ->groupBy('specification');

        return $spec->map(function ($v, $k) {
            return ['name' => $k, 'valueList' => $v];
        })->values();
    }

    // 保存足迹
    public function saveFootPrint($userId, $goodsId)
    {
        $footPrint = new FootPrint();
        $footPrint->fill(['user_id' => $userId, 'goods_id' => $goodsId]);
        return $footPrint->save();
    }

    // 获取常见问题
    public function getGoodsIssue($page = 1, int $limit = 4)
    {
        return Issue::query()->forPage($page, $limit)->get();
    }

    /**
     * 获取商品货品
     * @param  int  $goodsId
     * @return Builder[]|GoodsProduct[]
     */
    public function getGoodsProduct(int $goodsId)
    {
        return GoodsProduct::query()->where('goods_id', $goodsId)
            ->get();
    }

    public function getGoodsProductById(int $id)
    {
        return GoodsProduct::query()->find($id);
    }

    public function getGoodsProductByIds(array $ids)
    {
        if (empty($ids)) {
            return collect();
        }
        return GoodsProduct::query()->whereIn('id', $ids)->get();
    }

    /**
     * 获取在售商品的数量
     * @return int
     */
    public function countGoodsOnSale()
    {
        return Goods::query()->where('is_on_sale', 1)
            ->count('id');
    }

    public function listGoods(GoodsListInput $input, $columns)
    {
        $query = $this->getQueryByGoodsFilter($input);
        if (!empty($input->categoryId)) {
            $query = $query->where('category_id', $input->categoryId);
        }
        return $query->orderBy($input->sort, $input->order)->paginate($input->limit, $columns, 'page', $input->page);
    }

    public function listL2Category(GoodsListInput $input)
    {
        $query = $this->getQueryByGoodsFilter($input);
        $categoryIds = $query->select(['category_id'])->pluck('category_id')->unique()->toArray();
        return CatalogService::getInstance()->getL2ListByIds($categoryIds);
    }

    private function getQueryByGoodsFilter(GoodsListInput $input)
    {
        $query = Goods::query()->where('is_on_sale', 1);

        if (!empty($input->brandId)) {
            $query = $query->where('brand_id', $input->brandId);
        }
        if (!is_null($input->isNew)) {
            $query = $query->where('is_new', $input->isNew);
        }
        if (!is_null($input->isHot)) {
            $query = $query->where('is_hot', $input->isHot);
        }
        if (!empty($input->keyword)) {
            $query = $query->where(function (Builder $query) use ($input) {
                $query->where('keywords', 'like', '%' . $input->keyword . '%')
                    ->orWhere('name', 'like', '%' . $input->keyword . '%');
            });
        }

        return $query;
    }

    /**
     * 减库存
     * @param $productId
     * @param $num
     * @return int
     */
    public function reduceStock($productId, $num)
    {
        $product = $this->getGoodsProductById($productId);
        $product->number = $product->number - $num;
        return $product->cas();
    }

    /**
     * 加库存
     * @param $productId
     * @param $num
     * @return int
     */
    public function addStock($productId, $num)
    {
        $product = $this->getGoodsProductById($productId);
        $product->number = $product->number + $num;
        return $product->cas();
    }
}